<!--  -->
<template>
  <div class="domainBox">
    <div style="margin:24px 0;">
      <el-button size="small" type="primary" @click="addRedirect">增&nbsp;加</el-button>
    </div>
    <el-table v-loading="loading" size="medium" :data="domainData" border style="width: 100%">
      <el-table-column header-align="center" align="center" prop="fromDomain" label="访问域名" :resizable="false">
      </el-table-column>
      <el-table-column header-align="center" align="center" prop="toDomain" label="目标域名" :resizable="false">
      </el-table-column>
      <el-table-column width="80" header-align="center" align="center" fixed="right" label="操作" :resizable="false">
        <template slot-scope="scope">
          <el-button @click="deleteitem(scope.row)" type="text" size="small">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <Add ref="add" :resetData="resetData" />
  </div>
</template>

<script>
import Add from '@/components/main/user/host/domain/redirect/Add.vue'
// import * as WindowType from '@/config/windowtype.js'
import * as PubsubType from '@/config/pubsubtype.js'
import PubSub from 'pubsub-js'
export default {
  created () {
    this.resetData()
    PubSub.subscribe(PubsubType.PUBSUB_DELETE_DOMAIN_PUSH, () => {
      this.resetData()
    })
  },
  data () {
    return {
      formInline: {
        domain: ''
      },
      domainData: [],
      loading: false
    }
  },
  methods: {
    resetData () {
      this.loading = true
      this.$post('/domain/redirect-list').then(response => {
        if (response && response.from && response.from.length > 0) {
          this.domainData = initData(response)
        } else {
          this.domainData = []
        }
        this.loading = false
      })
    },
    addRedirect () {
      this.$refs['add'].show()
    },
    deleteitem (data) {
      this.$confirm('确定要删除 ' + data.fromDomain + ' 跳转到 ' + data.toDomain + ' 的域名重定向', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.loading = true
        this.$post('/domain/delete-redirect', { id: data.id }).then(response => {
          if (response && parseInt(response) > 0) {
            this.resetData()
          }
        })
      }).catch(() => {
      })
    }
  },
  components: {
    Add
  }
}

function initData (response) {
  return response.from.map(element => {
    let item = response.to.find(ele => {
      return parseInt(ele.id) === parseInt(element.redirect)
    })
    if (item) {
      return {
        id: element.id,
        fromDomain: element.domainName,
        toDomain: item.domainName
      }
    }
  })
}

</script>
<style scoped>
.domainBox /deep/ .el-table th {
  background: #EFF1F8;
  color: #555;
  border-color: #fff;
}
.domainBox /deep/ .el-table__fixed-right{
  height: 100% !important;
}
</style>
